package org.jeecg.modules.front.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.thirdpartyapi.dto.AuthUserInfoDto;
import org.jeecg.modules.dzswj.DESUtil;
import org.jeecg.modules.dzswj.GuangdongSfjrApiService;
import org.jeecg.modules.dzswj.vo.request.SmzyhdlReqVo;
import org.jeecg.modules.dzswj.vo.response.DzswjBaseResponse;
import org.jeecg.modules.dzswj.vo.response.PzjgxxVo;
import org.jeecg.modules.dzswj.vo.response.SmzdlResponseVo;
import org.jeecg.modules.dzswj.vo.response.nsrxxcx.Nsrjbxx;
import org.jeecg.modules.dzswj.vo.response.nsrxxcx.NsrxxCxResponseVo;
import org.jeecg.modules.fk.entity.DjOrg;
import org.jeecg.modules.fk.service.IDjOrgService;
import org.jeecg.modules.front.vo.AuthReqVo;
import org.jeecg.modules.qyxx.entity.DjNsrxxPO;
import org.jeecg.modules.qyxx.enumdemo.RedisKeyConstant;
import org.jeecg.modules.qyxx.service.IDjNsrxxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author chensherun on 2022/3/9.
 * @version 1.0
 */
@Api(value = "用户授权", tags = "用户授权")
@Slf4j
@RestController
@RequestMapping("/front/auth")
public class AuthController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private GuangdongSfjrApiService sfjrApiService;

    @Autowired
    private IDjNsrxxService djNsrxxService;

    @Autowired
    private IDjOrgService djOrgService;

    @ApiOperation(value = "电局授权")
    @PostMapping("/smrz")
    public Result<?> auth(@RequestBody AuthReqVo authVo) {
        String fullKey = RedisKeyConstant.AUTH_USER_KEY + authVo.getKey();
        String dataStr = redisUtil.getString(fullKey);
        if (StringUtils.isBlank(dataStr)) {
            return Result.noauth("登录信息已失效");
        }
        AuthUserInfoDto authUserInfoDto = JSONObject.parseObject(dataStr, AuthUserInfoDto.class);
        if (authUserInfoDto == null || StringUtils.isBlank(authUserInfoDto.getMobilePhone())) {
            log.error("从redis获取的信息有误，fullKey:{}, value:{}", fullKey, dataStr);
            return Result.noauth("登录信息已失效");
        }
        redisUtil.setString(fullKey, dataStr, RedisKeyConstant.AUTH_USER_KEY_EXPIRE);

        //客户列表
        DjOrg djOrg = djOrgService.getByNsrsbhOrShxydm(authVo.getNsrsbh());
        //是否已经授权过
        if (djOrg != null && djOrg.getIsAuth() == 1 && StringUtils.isNotBlank(djOrg.getRealYhm())) {
            //如果是同一个用户授权的，可以覆盖授权
            if (!authUserInfoDto.getMobilePhone().equals(djOrg.getAutherMobile())) {
                return Result.error("该企业已经授权！");
            }
        }
        String mobile = authUserInfoDto.getMobilePhone();
        SmzyhdlReqVo smzyhdlReqVo = new SmzyhdlReqVo();
        smzyhdlReqVo.setYhm(authVo.getYhm());
        smzyhdlReqVo.setPassword(authVo.getPassword());
        SmzdlResponseVo.Body djyhmhmmdljk = sfjrApiService.djyhmhmmdljk(smzyhdlReqVo);
        //判断是否存在dj_org (mysql和oracle)
        SmzdlResponseVo.SsoLoginInfo ssoLoginInfo = djyhmhmmdljk.getSsoLoginInfo();
        SmzdlResponseVo.Smzxx smzxx = ssoLoginInfo.getSmzxx();
        List<SmzdlResponseVo.Nsr> nsrs = ssoLoginInfo.getNsrs();
        Set<String> djxhSet = new HashSet<>();
        for (SmzdlResponseVo.Nsr nsrVo : nsrs) {
            if ("N".equals(nsrVo.getTybz()) && (authVo.getNsrsbh().equals(nsrVo.getGsnsrsbh()) || authVo.getNsrsbh().equals(nsrVo.getShxydm()))) {
                //nsr = nsrVo;
                djxhSet.add(nsrVo.getGszdjxh());
            }
        }
        if (djxhSet.size() == 0) {
            throw new JeecgBootException("实名账号没有绑定该企业");
        }
        DjNsrxxPO djNsrxx = djNsrxxService.getByNsrsbhOrShxydm(authVo.getNsrsbh());
        //纳税人表信息 dj_nsrxx, dj_nsrzyxx
        if (djNsrxx == null) {
            //查询电局接口添加
            NsrxxCxResponseVo nsrxxCxResponseVo = null;
            for (String djxh : djxhSet) {
                NsrxxCxResponseVo nsrxxCxResponseVoTemp = sfjrApiService.nsrxxCx(djyhmhmmdljk.getSsoSessionId(), null, djxh);
                Nsrjbxx nsrjbxx = nsrxxCxResponseVoTemp.getNsrjbxx();
                //只保存满足条件的djxh对应的企业信息
                if ("N".equals(nsrjbxx.getKqccsztdjbz()) && Integer.valueOf(nsrjbxx.getKzztdjlxdm()) <= 1110 && "Y".equals(nsrjbxx.getYxbz())) {
                    nsrxxCxResponseVo = nsrxxCxResponseVoTemp;
                    break;
                }
            }
            Nsrjbxx nsrjbxx = nsrxxCxResponseVo.getNsrjbxx();
            String tynsrsbh = com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(nsrjbxx.getShxyDm()) ? nsrjbxx.getShxyDm() : nsrjbxx.getNsrsbh();
            DzswjBaseResponse<List<PzjgxxVo>> pzjgxxResponse = sfjrApiService.nsrxxPzjgxx(djyhmhmmdljk.getSsoSessionId(), nsrjbxx.getZgswjdm(), tynsrsbh);
            List<PzjgxxVo> pzjgxxVoList = pzjgxxResponse.getBody();
            djNsrxx = djNsrxxService.saveOrUpdateNsrjbxxAndPzjg(nsrxxCxResponseVo, pzjgxxVoList);
        }

        //存在则更新
        if (djOrg == null) {
            djOrg = new DjOrg();
            djOrg.setOrgId(djNsrxx.getTynsrsbh());
            djOrg.setDjxh(djNsrxx.getTynsrsbh());
            djOrg.setNsrsbh(djNsrxx.getNsrsbh());
            djOrg.setShxydm(djNsrxx.getShxydm());
            djOrg.setNsrmc(djNsrxx.getNsrmc());
        }
        //授权人手机号，授权人名称， 授权电局账号，授权电局名称
        djOrg.setRealYhm(authVo.getYhm());
        String encryptPw = null;
        try {
            encryptPw = DESUtil.encrypt(authVo.getPassword(), GuangdongSfjrApiService.DB_PASS_KEY);
        } catch (Exception e) {
            //日志
            throw new JeecgBootException("系统异常");
        }
        djOrg.setPassword(encryptPw);
        djOrg.setAutherMobile(mobile);
        if (smzxx != null) {
            djOrg.setAutherName(smzxx.getXm());
        }
        djOrgService.saveOrUpdate(djOrg);
        return Result.OK("授权成功");
    }



    @ApiOperation(value = "获取用户信息")
    @GetMapping("/getUserInfo")
    public Result<?> getUserInfo(@RequestParam String key) {
        String fullKey = RedisKeyConstant.AUTH_USER_KEY + key;
        String dataStr = redisUtil.getString(fullKey);
        if (StringUtils.isNotBlank(dataStr)) {
            redisUtil.setString(fullKey, dataStr, RedisKeyConstant.AUTH_USER_KEY_EXPIRE);
            AuthUserInfoDto authUserInfoDto = JSONObject.parseObject(dataStr, AuthUserInfoDto.class);
            if (authUserInfoDto != null) {
                return Result.OK(authUserInfoDto);
            }
        }
        return Result.noauth("登录信息已失效");
    }
}
